package common.library.activities;

import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import common.library.models.Callback;

//declared activity in AndroidManifest.xml
public class ApplyPermissionsActivity extends AppCompatActivity {

    public static String[] permissions;

    boolean check() {
        for (String permission : permissions)
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED)
                return false;
        return true;
    }

    void apply() {
        if (check())
            onRequestPermissionsResult(0, permissions, new int[permissions.length]);
        else
            requestPermissions(permissions, 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apply();
    }

    public static boolean check(int[] grantResults) {
        for (int grantResult : grantResults)
            if (grantResult != 0)
                return false;
        return true;
    }

    public static Callback callback;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (check(grantResults)) {
            finish();
            if (callback != null)
                callback.run();
            return;
        }
        apply();
    }
}